//
//  YFNetworkingService.m
//  CoollangTennisBall
//
//  Created by Coollang on 2018/1/12.
//  Copyright © 2018年 Coollang-YF. All rights reserved.
//

#import "YFNetworkingService.h"

NSString * const QiNiuErrorDomainCustom = @"QiNiuErrorDomainCustom";

@implementation YFNetworkingService {
    __weak FUIAlertView *_failAlertView;
}
+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

+ (QNUploadManager *)qNUploadManager {
    static QNUploadManager *_qn_UpManager = nil;
    if (_qn_UpManager == nil) {
        QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
            // 华南地区
            builder.zone = [QNFixedZone zone2];
        }];
        _qn_UpManager = [[QNUploadManager alloc] initWithConfiguration:config];
    }
    return _qn_UpManager;
}
-(void)configureBaseUrl {
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    
    config.baseUrl = kBaseUrl;
    
//    [self setupRequestFilters];
    // 配置缓存
    if ([DataModel shouldAutoLogin]) {
        [self setUpRequestCacheFiltersWithUserId:[DataModel lastLoginID]];
    }
    
    // 开启网络监控
    [YFCheckNetworkStatus shareInstance];
    [[YTKNetworkAgent sharedAgent] setValue:[NSSet setWithObjects:
                                             @"application/json",
                                             @"text/html",
                                             @"text/plain",
                                             @"text/javascript",
                                             @"image/jpeg",
                                             @"image/png",
                                             @"application/octet-stream",
                                             @"text/json",
                                             nil]
                                 forKeyPath:@"jsonResponseSerializer.acceptableContentTypes"];
}

- (void)setupRequestFilters {
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    YFUrlArgumentsFilter *urlFilter = [YFUrlArgumentsFilter filterWithArguments:@{@"version": appVersion}];
    [config addUrlFilter:urlFilter];
}
// 配置缓存
- (void)setUpRequestCacheFiltersWithUserId:(NSString *)userId {
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    [config clearCacheDirPathFilter];
    YFUrlCacheDirPathFilter *cacheFilter = [YFUrlCacheDirPathFilter filterWithArguments:userId];
    [config addCacheDirPathFilter:cacheFilter];
}

- (void)cancelRequest:(YFBaseRequest *)request{
    [request stop];
}

//一般的请求
-(void)sendRequest:(YFBaseRequest *)request
          callback:(YFNetworkingServiceBlock)block {
    
    [request startWithCompletionBlockWithSuccess:^(YTKBaseRequest *req) {
        NSLog(@"responseJsonString:%@",request.responseString);
        NSString * result = req.responseJSONObject[@"ret"];
        // 错误处理
        NSLog(@"%@",req.responseObject[@"errDesc"]);
        if (result.integerValue == WebRespondTypeSuccess || [result isEqualToString:@"200"]){
            if (block){ block(YES,req,nil);}
        }else {
            NSError *error = [request disposeRequestErrorWithRet:result];
            request.reqError = error;
            if (block){ block(NO,req,error);}
            [self showNetErrorFailAlertWithError:error netErrorTipType:request.netErrorTipType];
            
            [self showNetErrorFailAlertWithError:error netErrorTipType:request.netErrorTipType];
            [self showNetErrorFailAlertWithError:error netErrorTipType:request.netErrorTipType];
        }
    } failure:^(YTKBaseRequest *req) {
        NSError *error;
        if([YFCheckNetworkStatus isReachable] == NO){
            error = [YFNetError creatErrorWithRet:WebRespondTypeNotReachable];
        }else {
            if ([[req.responseObject allKeys] containsObject:@"ret"]){
                error = [request disposeRequestErrorWithRet:req.responseJSONObject[@"ret"]];
            }else {
                // 这里的错误处理情况要复杂一点,要处理 404 501 等系统错误
                if (req.response.statusCode == WebRespondTypeServiceError || req.response.statusCode == WebRespondTypeServiceError404) {
                    error = [YFNetError creatErrorWithRet:req.responseStatusCode];
                }else {
                    error = req.error;
                }
            }
        }
        request.reqError = error;
         [self showNetErrorFailAlertWithError:error netErrorTipType:request.netErrorTipType];
        if (block) {
            block(NO,req,error);
        }
    }];
}

//并发请求
-(void)sendBatch:(NSArray *)requestArray
        callback:(YFNetworkingServiceBlock)block {
    YTKBatchRequest *batchRequest = [[YTKBatchRequest alloc] initWithRequestArray:requestArray];
    [batchRequest startWithCompletionBlockWithSuccess:^(YTKBatchRequest *batchRequest) {
        if (block){
            block(YES,batchRequest,nil);
        }
    } failure:^(YTKBatchRequest *batchRequest) {
        if (block){
            block(NO,batchRequest,[YFNetError creatErrorWithRet:WebRespondTypeOther]);
        }
    }];
}

#pragma mark - 下载文件
- (void)performDownloadNewVersionWithPath:(NSString *)downloadPath downloadCompletionBlock:(DownloadCompletionBlock)block
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:downloadPath];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    request.timeoutInterval = 15;
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:block];
    [downloadTask resume];
}

- (void)showNetErrorFailAlertWithError:(NSError *)netError netErrorTipType:(kNetErrorTipType)errorTipType {
    
    if (netError.code == WebRespondTypeNotLogin || netError.code == WebRespondTypeEmailInvalid || netError.code == WebRespondTypePasswordInvalid){
        if (_failAlertView == nil) {
            FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Log on invalid,please log in again", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
            alertView.onOkAction = ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkingManagerLoginFailNotification object:nil];
            };
            [alertView customizeAppearance];
            [alertView show];
            _failAlertView = alertView;
        }
    }else {
        
    }
}


- (void)showLoginFailAlertView {
    if (_failAlertView == nil) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Log on invalid,please log in again", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
        alertView.onOkAction = ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkingManagerLoginFailNotification object:nil];
        };
        [alertView customizeAppearance];
        [alertView show];
        
        _failAlertView = alertView;
    }
}



@end
